package com.gray.blog.common.config;

import cn.hutool.core.util.StrUtil;
import com.gray.blog.common.util.JWTUtil;
import com.gray.blog.dao.sys.SysUserDao;
import com.gray.blog.dto.UserRoleInfoDTO;
import java.util.HashSet;
import java.util.Set;
import org.apache.shiro.authc.AccountException;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * Created  By zhoux 2019/01/09
 **/
@Component
public class CustomRealmConfig extends AuthorizingRealm {

    private SysUserDao sysUserDao;

    @Autowired
    private void setSysUserDao(SysUserDao sysUserDao) {
        this.sysUserDao = sysUserDao;
    }


    public boolean supports(AuthenticationToken token) {
        return token instanceof JWTToken;
    }

    /**
     * 获取授权信息
     * @param principalCollection
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        String username = JWTUtil.getUsername(principalCollection.toString());
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        Set<String> roleSet = new HashSet<>();
        // 获取用户最大角色
        UserRoleInfoDTO userRoleInfoDTO = sysUserDao.getUserMaximumAuthority(username);
        roleSet.add(userRoleInfoDTO == null ? null : userRoleInfoDTO.getRoleEnName());
        //设置该用户拥有的角色
        info.setRoles(roleSet);
        return info;
    }

    /**
     * 获取身份验证信息
     * Shiro中，最终是通过 Realm 来获取应用程序中的用户、角色及权限信息的。
     * @param authenticationToken
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        String token = (String) authenticationToken.getCredentials();
        String username = JWTUtil.getUsername(token);
        String password = sysUserDao.getPasswordByLoginName(username);
        if (StrUtil.isBlank(password)) {
            throw new AccountException("登录信息有误");
        }
        return new SimpleAuthenticationInfo(token, token, "MyRealm");
    }


}
